//
//  TYZPageViewController.m
//  AVfoundationDemo
//
//  Created by TangBin on 2019/8/14.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "TYZPageViewController.h"
#import "TYZPageHeaderScrollView.h"
#import "UIScrollView+TYZPage.h"

#define kDEFAULT_INSET_BOTTOM 400

@interface TYZPageViewController () <UIScrollViewDelegate, TYZPageScrollMenuViewDelegate>

/// 一个HeaderView的背景View
@property (nonatomic, strong) TYZPageHeaderScrollView *headerBgView;

/// 页面ScrollView
@property (nonatomic, strong) TYZPageScrollView *pageScrollView;

/// 背景ScrollView
@property (nonatomic, strong, readwrite) TYZPageScrollView *bgScrollView;

/// 展示控制器的字典 最多只会有两个，一个当前显示的VC，一个是将要显示的VC。最终只有一个当前显示的VC。
@property (nonatomic, strong) NSMutableDictionary *displayDictM;

/// 原始InsetBottom
@property (nonatomic, strong) NSMutableDictionary *originInsetBottomDictM;

/// 字典控制器的缓存 -  用来存储控制器的
@property (nonatomic, strong) NSMutableDictionary *cacheViewControllerDict;

/// 字典ScrollView的缓存 UITableView
@property (nonatomic, strong) NSMutableDictionary *scrollViewCacheDictionryM;

/// 当前显示的页面
@property (nonatomic, strong) UIScrollView *currentScrollView;

/// 当前控制器
@property (nonatomic, strong) UIViewController *currentViewController;

/// 上次偏移的位置
@property (nonatomic, assign) CGFloat lastPositionX;

/// TableView距离顶部的偏移量
@property (nonatomic, assign) CGFloat insetTop;

/// 判断headerView是否在列表内
@property (nonatomic, assign) BOOL headerViewInTableView;

/// 菜单栏的初始OriginY
@property (nonatomic, assign) CGFloat scrollMenuViewOriginY;

/// headerView的原始高度 用来处理头部伸缩效果
@property (nonatomic, assign) CGFloat headerViewOriginHeight;

/// 是否是悬浮状态
@property (nonatomic, assign) BOOL supendStatus;

/// 记录bgScrollView Y 偏移量
@property (nonatomic, assign) CGFloat beginBgScrollOffsetY;

/// 记录currentScrollView Y 偏移量
@property (nonatomic, assign) CGFloat beginCurrentScrollOffsetY;

/**
 初始化背景headerView
 */
- (void)initWithHeaderBgView;

- (void)initWithPageScrollView;

- (void)initWithScrollMenuView;

@end

@implementation TYZPageViewController

- (void)dealloc
{
    debugMethod();
}

/**
 *  初始化变量
 */
- (void)initWithVar
{
    [super initWithVar];
    
    // 判断headerView是否在列表内
    _headerViewInTableView = YES;
    
    
}

/**
 *  初始化navbar视图
 */
- (void)initWithNavBar
{
    [super initWithNavBar];
    
}

/**
 *  初始化子视图
 */
- (void)initWithSubView
{
    [super initWithSubView];
    
    [self setupSubViews];
    
    [self setSelectedPageIndex:self.pageIndex];
}

- (void)setupSubViews
{
    // 初始化背景headerView
    [self initWithHeaderBgView];
    
    [self initWithScrollMenuView];
    
    [self initWithPageScrollView];
}

/**
 初始化背景headerView
 */
- (void)initWithHeaderBgView
{
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle] || [self isSuspensionTopPauseStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView底部 || 菜单视图悬浮，刷新控件在HeaderView顶部 || 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
#if DEBUG
        NSAssert(self.headerView, @"please set headerView");
#endif
        _headerBgView = [[TYZPageHeaderScrollView alloc] initWithFrame:self.headerView.bounds];
        self.headerBgView.contentSize = CGSizeMake(kScreenWidth * 2, self.headerView.height);
        [self.headerBgView addSubview:self.headerView];
        self.headerViewOriginHeight = self.headerBgView.height;
        self.headerBgView.scrollEnabled = !self.config.headerViewCouldScrollPage;
//        debugLogFrameName(@"headerView.bounds=", self.headerView.bounds);
//        debugLogSizeName(@"bgview.conentsiez", self.headerBgView.contentSize);
        if (self.config.headerViewCouldScale && self.scaleBackgroundView)
        {
            [self.headerBgView insertSubview:self.scaleBackgroundView atIndex:0];
            self.scaleBackgroundView.userInteractionEnabled = NO;
        }
        self.config.tempTopHeight = self.headerBgView.height + self.config.menuHeight;
        _insetTop = self.headerBgView.height + self.config.menuHeight;
        self.scrollMenuViewOriginY = _headerView.height;
        
        if ([self isSuspensionTopPauseStyle])
        {
            _insetTop = self.headerBgView.height - self.config.suspenOffsetY;
            [self.bgScrollView addSubview:self.headerBgView];
        }
        
    }
}

/**
 初始化pageScrollView
 */
- (void)initWithPageScrollView
{
    CGFloat navHeight = (self.config.showNavigation ? NAVBAR_HEIGHT_STATUS : 0);
    CGFloat tabHeight = (self.config.showTabbar ? self.config.tabbarHeight : 0);
    // 裁剪内容高度 用来添加最上层控件 添加在父类view上
    CGFloat cutOutHeight = (self.config.cutOutHeight > 0 ? self.config.cutOutHeight : 0);
    // 主视图的高度
    CGFloat contentHeight = kScreenHeight - navHeight - tabHeight - cutOutHeight;
    
    if ([self isSuspensionTopPauseStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
        self.bgScrollView.frame = CGRectMake(0, 0, kScreenWidth, contentHeight);
        self.bgScrollView.contentSize = CGSizeMake(kScreenWidth, contentHeight + self.headerBgView.height - self.config.suspenOffsetY);
        
        self.scrollMenuView.top = self.headerBgView.bottom;
        
        self.pageScrollView.frame = CGRectMake(0, self.scrollMenuView.bottom, kScreenWidth, contentHeight - self.config.menuHeight - self.config.suspenOffsetY);
        self.pageScrollView.contentSize = CGSizeMake(kScreenWidth * self.controllerList.count, self.pageScrollView.height);
        self.config.contentHeight = self.pageScrollView.height;
        [self.bgScrollView addSubview:self.pageScrollView];
//        #define kLESS_THAN_iOS11 ([[UIDevice currentDevice].systemVersion floatValue] < 11.0 ? YES : NO)
        if ([[UIDevice currentDevice].systemVersion floatValue] < 11.0)
        {
            [self.view addSubview:[UIView new]];
        }
        [self.view addSubview:self.bgScrollView];
    }
    else
    {
        float y = ([self isTopStyle]?self.config.menuHeight:0);
        float height = ([self isTopStyle]?contentHeight - self.config.menuHeight:contentHeight);
        CGRect frame = CGRectMake(0, y, kScreenWidth, height);
        self.pageScrollView.frame = frame;
        
        self.pageScrollView.contentSize = CGSizeMake(kScreenWidth * self.controllerList.count, contentHeight - ([self isTopStyle]?self.config.menuHeight : 0));
        
        self.config.contentHeight = self.pageScrollView.height - self.config.menuHeight;
        if ([[UIDevice currentDevice].systemVersion floatValue] < 11.0)
        {
            [self.view addSubview:[UIView new]];
        }
        [self.view addSubview:self.pageScrollView];
    }
}

/**
 初始化菜单
 */
- (void)initWithScrollMenuView
{
    CGRect frame = CGRectMake(0, 0, self.config.menuWidth, self.config.menuHeight);
    [self initWithPagescrollMenuViewFrame:frame];
}

/**
 将headerView从view 上 放置 tableview 上
 */
- (void)replaceHeaderViewFromView
{
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView底部 || 菜单视图悬浮，刷新控件在HeaderView顶部
        if (!self.headerViewInTableView)
        {// headerView 不在列表内
            UIScrollView *scrollView = self.currentScrollView;
            CGFloat headerViewY = [self.headerBgView.superview convertRect:self.headerBgView.frame toView:scrollView].origin.y;
            CGFloat scrollMenuViewY = [self.scrollMenuView.superview convertRect:self.scrollMenuView.frame toView:scrollView].origin.y;
            
            [self.headerBgView removeFromSuperview];
            [self.scrollMenuView removeFromSuperview];
            
            self.headerBgView.top = headerViewY;
            self.scrollMenuView.top = scrollMenuViewY;
            
            [scrollView addSubview:self.headerBgView];
            [scrollView addSubview:self.scrollMenuView];
            
            _headerViewInTableView = YES;
        }
    }
}

/**
 将headerView 从 tableview 上 放置 view 上
 */
- (void)replaceHeaderViewFromTableView
{
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle])
    {
        if (_headerViewInTableView)
        {
            CGFloat headerViewY = [self.headerBgView.superview convertRect:self.headerBgView.frame toView:self.pageScrollView].origin.y;
            CGFloat scrollMenuViewY = [self.scrollMenuView.superview convertRect:self.scrollMenuView.frame toView:self.pageScrollView].origin.y;
            
            [self.headerBgView removeFromSuperview];
            [self.scrollMenuView removeFromSuperview];
            self.headerBgView.top = headerViewY;
            self.scrollMenuView.top = scrollMenuViewY;
            
            [self.view insertSubview:self.headerBgView aboveSubview:self.pageScrollView];
            [self.view insertSubview:self.scrollMenuView aboveSubview:self.headerBgView];
            
            _headerViewInTableView = NO;
        }
    }
}

/**
 最终效果 current 拖到指定时 bg 才能下拉， bg 悬浮时 current 才能上拉
 计算悬浮顶部偏移量 - bgScrollView

 @param scrollView scrollView description
 */
- (void)calcuSuspendTopPauseWithBgScrollView:(UIScrollView *)scrollView
{
    if ([self isSuspensionTopPauseStyle] && scrollView == self.bgScrollView)
    {
        CGFloat bg_OffsetY = scrollView.contentOffset.y;
        CGFloat current_OffsetY = self.currentScrollView.contentOffset.y;
        
        // 求出拖拽方向
        BOOL dragBottom = _beginBgScrollOffsetY - bg_OffsetY > 0 ? YES : NO;
        // 当前大于0时
        if (dragBottom && current_OffsetY > 0)
        {
            // 设置原来的
            [scrollView tyz_setContentOffsetY:_beginBgScrollOffsetY];
            // 设置实时滚动的 当前 偏移量
            _beginCurrentScrollOffsetY = current_OffsetY;
        }
        else if (_beginBgScrollOffsetY == _insetTop && _beginCurrentScrollOffsetY != 0)
        {// 初始 begin 时超过了 实时 设置
            [scrollView tyz_setContentOffsetY:_beginBgScrollOffsetY];
            _beginCurrentScrollOffsetY = current_OffsetY;
        }
        else if (bg_OffsetY >= _insetTop)
        {// 设置边界
            [scrollView tyz_setContentOffsetY:_insetTop];
            _beginCurrentScrollOffsetY = current_OffsetY;
        }
        else if (bg_OffsetY <= 0 && current_OffsetY > 0)
        {// 设置边界
            [scrollView tyz_setContentOffsetY:0];
        }
    }
}

/**
 计算悬浮顶部偏移量 - CurrentScrollView

 @param scrollView scrollView description
 */
- (void)calcuSuspendTopPauseWithCurrentScrollView:(UIScrollView *)scrollView
{
    if ([self isSuspensionTopPauseStyle])
    {
        if (!scrollView.isDragging)
        {
            return;
        }
        
        CGFloat bg_OffsetY = self.bgScrollView.contentOffset.y;
        CGFloat cur_OffsetY = scrollView.contentOffset.y;
        
        /// 求出拖拽方向
        BOOL dragBottom = _beginCurrentScrollOffsetY - cur_OffsetY < 0 ? YES : NO;
        /// cu 是大于 0 的 且 bg 要小于 _insetTop
        if (dragBottom && cur_OffsetY > 0 && bg_OffsetY < _insetTop)
        {
            /// 设置之前的拖动位置
            [scrollView tyz_setContentOffsetY:_beginCurrentScrollOffsetY];
            /// 修改 bg 原先偏移量
            _beginBgScrollOffsetY = bg_OffsetY;
        }
        else if (cur_OffsetY < 0)
        {/// cu 拖到 小于 0 就设成0
            [scrollView tyz_setContentOffsetY:0];
        }
        else if (bg_OffsetY >= _insetTop)
        {/// bg 超过了 insetTop 就设置初始化为 _insetTop
            _beginBgScrollOffsetY = _insetTop;
        }
    }
}

/**
 移除缓存控制器
 */
- (void)removeViewController
{
    NSString *title = [self titleWithIndex:self.pageIndex];
    NSString *displayKey = [self getKeyWithTitle:title];
//    debugLog(@"%s -- title=%@ ; displayKey=%@", __func__, title, displayKey);
    for (NSString *tmpkey in self.displayDictM.allKeys)
    {
//        debugLog(@"%s--tmpKey=%@; key=%@", __func__, tmpkey, displayKey);
        if (![tmpkey isEqualToString:displayKey])
        {
            [self removeViewControllerWithChildVC:self.displayDictM[tmpkey] withKey:tmpkey];
        }
    }
}

/**
 从父控制器移除控制器

 @param childVC 子控制器
 @param key key
 */
- (void)removeViewControllerWithChildVC:(UIViewController *)childVC withKey:(NSString *)key
{
//    debugMethod();
    [self removeViewControllerWithChildVC:childVC];
    [self.displayDictM removeObjectForKey:key];
    if (![self.cacheViewControllerDict objectForKey:key])
    {
        [self.cacheViewControllerDict setObject:childVC forKey:key];
    }
}

/**
  添加子控制器

 @param childVC childVC description
 @param parentVC parentVC description
 */
- (void)addChildViewControllerWithChildVC:(UIViewController *)childVC parentVC:(UIViewController *)parentVC
{
    [parentVC addChildViewController:childVC];
    [parentVC didMoveToParentViewController:childVC];
    [parentVC.view addSubview:childVC.view];
}

/**
 y子控制器移除自己

 @param childVC childVC description
 */
- (void)removeViewControllerWithChildVC:(UIViewController *)childVC
{
    [childVC.view removeFromSuperview];
    [childVC willMoveToParentViewController:nil];
    [childVC removeFromParentViewController];
}

#pragma mark - 初始化PageScrollMenView

/**
 初始化PageScrollMenView

 @param frame frame description
 */
- (void)initWithPagescrollMenuViewFrame:(CGRect)frame
{
    _scrollMenuView = [TYZPageScrollMenuView pageScrollMenuViewWithFrame:frame titles:self.titlesList configration:self.config delegate:self currentIndex:self.pageIndex];
    switch (self.config.pageStyle)
    {
        case TYZPageStyleTop:
        {// 菜单视图在顶部
            
        }
        case TYZPageStyleSuspensionTop:
        {// 菜单视图悬浮，刷新控件在HeaderView顶部
            
        }
        case TYZPageStyleSuspensionCenter:
        {// 菜单视图悬浮，刷新控件在HeaderView底部
            [self.view addSubview:self.scrollMenuView];
        } break;
        case TYZPageStyleNavigation:
        {// 菜单视图在系统导航栏中
            UIViewController *vc;
            if ([self.parentViewController isKindOfClass:[UINavigationController class]])
            {
                vc = self;
            }
            else
            {
                vc =self.parentViewController;
            }
            vc.navigationItem.titleView = self.scrollMenuView;
        } break;
        case TYZPageStyleSuspensionTopPause:
        {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
            [self.bgScrollView addSubview:self.scrollMenuView];
        } break;
        default:
            break;
    }
}

#pragma mark - 初始化字控制器

/**
  初始化子控制器

 @param index index description
 */
- (void)initWithViewControllerIndex:(NSInteger)index
{
    self.currentViewController = self.controllerList[index];
    self.pageIndex = index;
    NSString *title = [self titleWithIndex:index];
//    debugLog(@"%s--title=%@; cacheViewControllerDict.count=%zd", __func__, title, self.cacheViewControllerDict.count);
    if ([self.displayDictM objectForKey:[self getKeyWithTitle:title]])
    {
        return;
    }
//    debugLog(@"准备添加视图控制器");
    UIViewController *cacheVC = [self.cacheViewControllerDict objectForKey:[self getKeyWithTitle:title]];
    cacheVC = (cacheVC==nil?self.controllerList[index]:cacheVC);
    [self addChildViewControllerToParent:cacheVC index:index];
}

/**
 添加子控制器到父控制器中

 @param childController 子控制器
 @param index index
 */
- (void)addChildViewControllerToParent:(UIViewController *)childController index:(NSInteger)index
{
    [self addChildViewController:self.controllerList[index]];
    childController.view.frame = CGRectMake(kScreenWidth * index, 0, self.pageScrollView.width, self.pageScrollView.height);
    [self.pageScrollView addSubview:childController.view];
    
    NSString *title = [self titleWithIndex:index];
    NSString *key = [self getKeyWithTitle:title];
    [self.displayDictM setObject:childController forKey:key];
    
    UIScrollView *scrollView = self.currentScrollView;
//    NSLog(@"1.contentOffset==%@", NSStringFromCGPoint(scrollView.contentOffset));
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(pageViewController:heightForScrollViewAtIndex:)])
    {
       CGFloat scrollViewHeight = [self.dataSource pageViewController:self heightForScrollViewAtIndex:index];
        scrollView.frame = CGRectMake(0, 0, childController.view.width, scrollViewHeight);
    }
    else
    {
        scrollView.frame = childController.view.bounds;
    }
    
    [childController didMoveToParentViewController:self];
    
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView底部 || 菜单视图悬浮，刷新控件在HeaderView顶部
        if (![self.cacheViewControllerDict objectForKey:key])
        {
            CGFloat bottom = (scrollView.contentInset.bottom > 2 * kDEFAULT_INSET_BOTTOM ? 0 : scrollView.contentInset.bottom);
            [self.originInsetBottomDictM setValue:@(bottom) forKey:key];
            
            // 设置TableView 内容偏移
            scrollView.contentInset = UIEdgeInsetsMake(_insetTop, 0, scrollView.contentInset.bottom + 3 * kDEFAULT_INSET_BOTTOM, 0);
        }
        if ([self isSuspensionBottomStyle])
        {
            scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(_insetTop, 0, 0, 0);
        }
        
        if (self.cacheViewControllerDict.count == 0)
        {
            // 初次添加headerView、scrollMenuView
            self.headerBgView.top = -_insetTop;
            self.scrollMenuView.top = self.headerBgView.bottom;
//            debugLog(@"scrolmenttop=%f", self.scrollMenuView.top);
            [scrollView addSubview:self.headerBgView];
            [scrollView addSubview:self.scrollMenuView];
            // 设置首次偏移量置顶
            [scrollView setContentOffset:CGPointMake(0, -_insetTop) animated:NO];
        }
        else
        {
            CGFloat scrollMenuViewY = [self.scrollMenuView.superview convertRect:self.scrollMenuView.frame toView:self.view].origin.y;
//            NSLog(@"self.supendstatus=%d", self.supendStatus);
            if (self.supendStatus)
            {
                // 首次已经悬浮 设置初始化 偏移量
                if (![self.cacheViewControllerDict objectForKey:key])
                {
                    [scrollView setContentOffset:CGPointMake(0, -self.config.menuHeight - self.config.suspenOffsetY) animated:NO];
                }
                else
                {
                    // 再次悬浮 已经加载过了 设置偏移量
                    if (scrollView.contentOffset.y < -self.config.menuHeight - self.config.suspenOffsetY)
                    {
                        [scrollView setContentOffset:CGPointMake(0, -self.config.menuHeight - self.config.suspenOffsetY) animated:NO];
                    }
                }
            }
            else
            {
                CGFloat scrollMenuViewDeltaY = _scrollMenuViewOriginY - scrollMenuViewY;
                scrollMenuViewDeltaY = -_insetTop + scrollMenuViewDeltaY;
//                NSLog(@"scrollMenuViewDeltaY=%f", scrollMenuViewDeltaY);
                // 求出偏移了多少 未悬浮（多个scrollView偏移量联动）
                scrollView.contentOffset = CGPointMake(0, scrollMenuViewDeltaY);
            }
        }
    }
    
    // 缓存控制器
    if (![self.cacheViewControllerDict objectForKey:key])
    {
        [self.cacheViewControllerDict setObject:childController forKey:key];
    }
}

#pragma mark - 初始化
/**
 初始化方法
 @param controllers 子控制器
 @param titles 标题
 @param config 配置信息
 */
+ (instancetype)pageWithControllers:(NSArray *)controllers titles:(NSArray *)titles config:(TYZPageConfigration *)config
{
    return [[self alloc] initPageWithControllers:controllers titles:titles config:config];
}
/**
 初始化方法
 @param controllers 子控制器
 @param titles 标题
 @param config 配置信息
 */
- (instancetype)initPageWithControllers:(NSArray *)controllers titles:(NSArray *)titles config:(TYZPageConfigration *)config
{
    if (self = [super init])
    {
        self.controllerList = controllers.mutableCopy;
        self.titlesList = titles.mutableCopy;
        self.config = config?:[TYZPageConfigration defaultConfigration];
        self.displayDictM = @{}.mutableCopy;
        self.cacheViewControllerDict = @{}.mutableCopy;
        self.originInsetBottomDictM = @{}.mutableCopy;
        self.scrollViewCacheDictionryM = @{}.mutableCopy;
    }
    return self;
}

#pragma mark - 样式取值

/**
 菜单样式是否在顶部

 @return return value description
 */
- (BOOL)isTopStyle
{
    return self.config.pageStyle == TYZPageStyleTop ? YES : NO;
}

/**
 菜单样式是否在导航栏

 @return return value description
 */
- (BOOL)isNavigationStyle
{
    return self.config.pageStyle == TYZPageStyleNavigation ? YES : NO;
}

/**
 菜单视图悬浮，刷新控件在HeaderView顶部

 @return return value description
 */
- (BOOL)isSuspensionTopStyle
{
    return self.config.pageStyle == TYZPageStyleSuspensionTop ? YES : NO;
}

/**
 菜单视图悬浮，刷新控件在HeaderView底部

 @return return value description
 */
- (BOOL)isSuspensionBottomStyle
{
    return self.config.pageStyle == TYZPageStyleSuspensionCenter ? YES : NO;
}

/**
 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面

 @return return value description
 */
- (BOOL)isSuspensionTopPauseStyle
{
    return self.config.pageStyle == TYZPageStyleSuspensionTopPause ? YES : NO;
}

/**
 根据index获取按钮的title

 @param index index
 @return return value description
 */
- (NSString *)titleWithIndex:(NSInteger)index
{
    return self.titlesList[index];
}

/**
 根据按钮title获取index

 @param title title description
 @return return value description
 */
- (NSInteger)getPageIndexWithTitle:(NSString *)title
{
    return [self.titlesList indexOfObject:title];
}

- (NSString *)getKeyWithTitle:(NSString *)title
{
    if ([self respondsToCustomCacheKey])
    {
        NSString *Id = [self.dataSource pageViewController:self customCacheKeyForIndex:self.pageIndex];
        return Id;
    }
    return title;
}

#pragma mark - lazy  methods getter setter
- (TYZPageScrollView *)bgScrollView
{
    if (!_bgScrollView)
    {
        _bgScrollView = [[TYZPageScrollView alloc] init];
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        _bgScrollView.delegate = self;
        _bgScrollView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *))
        {
            _bgScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _bgScrollView;
}

- (TYZPageScrollView *)pageScrollView
{
    if (!_pageScrollView)
    {
        _pageScrollView = [[TYZPageScrollView alloc] init];
        _pageScrollView.showsVerticalScrollIndicator = NO;
        _pageScrollView.showsHorizontalScrollIndicator = NO;
        _pageScrollView.scrollEnabled = self.config.pageScrollEnabled;
        _pageScrollView.pagingEnabled = YES;
        _pageScrollView.bounces = NO;
        _pageScrollView.delegate = self;
        _pageScrollView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *))
        {
            _pageScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _pageScrollView;
}

/**
 获取当前滚动的ScrollView

 @return 当前的
 */
- (UIScrollView *)currentScrollView
{
    return [self getScrollViewWithPageIndex:self.pageIndex];
}

- (void)setHeaderView:(UIView *)headerView
{
    _headerView = headerView;
    _headerView.height = ceil(headerView.height);
}


#pragma mark - Invoke Delegate Method
/**
 回调监听列表滚动代理

 @param offsetY offsetY description
 */
- (void)invokeDelegateForScrollWithOffsetY:(CGFloat)offsetY
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:contentOffsetY:progress:)])
    {
        switch (self.config.pageStyle)
        {
            case TYZPageStyleSuspensionTop:
            case TYZPageStyleSuspensionCenter:
            {
                CGFloat progress = 1 + (offsetY + self.scrollMenuView.height + self.config.suspenOffsetY)/(self.headerBgView.height - self.config.suspenOffsetY);
                progress = (progress > 1 ? 1 : progress);
                progress = (progress < 0 ? 0 : progress);
                [self.delegate pageViewController:self contentOffsetY:offsetY progress:progress];
            } break;
            case TYZPageStyleSuspensionTopPause:
            {
                CGFloat progress = offsetY / (self.headerBgView.height - self.config.suspenOffsetY);
                progress = (progress > 1 ? 1 : progress);
                progress = (progress < 0 ? 0 : progress);
                [self.delegate pageViewController:self contentOffsetY:offsetY progress:progress];
            } break;
            default:
            {
                [self.delegate pageViewController:self contentOffsetY:offsetY progress:1];
            } break;
        }
    }
}

#pragma mark - eeee

/**
 根据pageIndex获取数据源ScrollView

 @param pageIndex pageIndex description
 @return return value description
 */
- (UIScrollView *)getScrollViewWithPageIndex:(NSInteger)pageIndex
{
    NSString *title = [self titleWithIndex:self.pageIndex];
    NSString *key = [self getKeyWithTitle:title];
    UIScrollView *scrollView = nil;
    
    if (![self.scrollViewCacheDictionryM objectForKey:key])
    {
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(pageViewController:pageForIndex:)])
        {
            scrollView = [self.dataSource pageViewController:self pageForIndex:pageIndex];
            scrollView.tyz_observerDidScrollView = YES;
            __weak typeof(self) weakSelf = self;
            scrollView.pageScrollViewDidScrollView = ^(UIScrollView * _Nonnull scrollView) {
                [weakSelf tyz_pageScrollViewDidScrollView:scrollView];
            };
            
            if (self.config.pageStyle == TYZPageStyleSuspensionTopPause)
            {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
                scrollView.pageScrollViewBeginDragginScrollView = ^(UIScrollView * _Nonnull scrollView) {
                    [weakSelf tyz_pageScrollViewBeginDragginScrollView:scrollView];
                };
            }
            
            if (@available(iOS 11.0, *))
            {
                if (scrollView)
                {
                    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                }
            }
        }
        
        if (scrollView)
        {
            [self.scrollViewCacheDictionryM setObject:scrollView forKey:key];
        }
    }
    else
    {
        return [self.scrollViewCacheDictionryM objectForKey:key];
    }
    
#if DEBUG
    NSAssert(scrollView != nil, @"请设置pageViewController的数据源！");
#endif
    return scrollView;
}

/**
 处理头部伸缩

 @param offsetY offsetY description
 */
- (void)headerScaleWithOffsetY:(CGFloat)offsetY
{
    if (self.config.headerViewCouldScale && self.scaleBackgroundView)
    {
        CGFloat yOffset = offsetY + _insetTop;
        CGFloat xOffset = yOffset * 0.5;
        CGRect headerBgViewFrame = self.headerBgView.frame;
        CGRect scaleBgViewFrame = self.scaleBackgroundView.frame;
        if (self.config.headerViewScaleMode == TYZPageHeaderViewScaleModeTop)
        {
            if (yOffset < 0)
            {
                headerBgViewFrame.origin.y = yOffset - _insetTop;
                headerBgViewFrame.size.height = -yOffset + self.headerViewOriginHeight;
                
                scaleBgViewFrame.size.height = -yOffset + self.headerViewOriginHeight;
                scaleBgViewFrame.origin.x = xOffset;
                scaleBgViewFrame.size.width = kScreenWidth + fabs(xOffset) * 2; // fabs求绝对值
            }
        }
        else
        {
            if (yOffset < 0)
            {
                headerBgViewFrame.origin.y = yOffset - _insetTop;
                headerBgViewFrame.size.height = fabs(yOffset) + self.headerViewOriginHeight;
                
                scaleBgViewFrame.size.height = fabs(yOffset) + self.headerViewOriginHeight;
                scaleBgViewFrame.origin.x = xOffset;
                scaleBgViewFrame.size.width = kScreenWidth + fabs(xOffset) * 2;
            }
        }
        self.headerBgView.frame = headerBgViewFrame;
        self.scaleBackgroundView.frame = scaleBgViewFrame;
    }
}


- (void)updateViewWithIndex:(NSInteger)pageIndex
{
    self.pageScrollView.contentSize = CGSizeMake(kScreenWidth * self.controllerList.count, self.pageScrollView.height);
    
    UIViewController *vc = self.controllerList[pageIndex];
    vc.view.left = kScreenWidth * pageIndex;
    
    [self.scrollMenuView reloadWithView];
    [self.scrollMenuView selectedItemIndex:pageIndex animated:NO];
    
    CGRect frame = CGRectMake(self.pageScrollView.width * pageIndex, 0, self.pageScrollView.width, self.pageScrollView.height);
    [self.pageScrollView scrollRectToVisible:frame animated:NO];
    
    [self scrollViewDidEndDecelerating:self.pageScrollView];
    self.pageIndex = pageIndex;
}

- (BOOL)respondsToCustomCacheKey
{
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(pageViewController:customCacheKeyForIndex:)])
    {
        return YES;
    }
    return NO;
}

#pragma mark - public methods

/**
 *  当前PageScrollViewVC作为子控制器
 *  @param parentViewControler 父类控制器
 */
- (void)addSelfToParentViewController:(UIViewController *)parentViewControler
{
    [self addChildViewControllerWithChildVC:self parentVC:parentViewControler];
}

/**
 *  从父类控制器里面移除自己（PageScrollViewVC）
 */
- (void)removeSelfViewController
{
    [self removeViewControllerWithChildVC:self];
}

/**
 刷新数据页面、所有View、菜单栏、headerView - 默认移除缓存控制器
 刷新菜单栏配置 标题数组
 
 e.g: vc.config = ...
 vc.titlesM = [self getArrayTitles].mutableCopy;
 
 如果需要重新走控制器的ViewDidLoad方法则需要重新赋值 controllers
 e.g:
 vc.controllersM = [self getArrayVCs].mutableCopy;
 */
- (void)reloadData
{
//    debugMethod();
    self.pageIndex = (self.pageIndex < 0 ? 0 : self.pageIndex);
    self.pageIndex = (self.pageIndex >= self.controllerList.count ? self.controllerList.count - 1 : self.pageIndex);
    
    for (UIViewController *vc in self.displayDictM.allValues)
    {
        [self removeViewControllerWithChildVC:vc];
    }
    [self.displayDictM removeAllObjects];
    
    [self.originInsetBottomDictM removeAllObjects];
    [self.cacheViewControllerDict removeAllObjects];
    [self.scrollViewCacheDictionryM removeAllObjects];
    [self.headerBgView removeFromSuperview];
    [self.bgScrollView removeFromSuperview];
    [self.pageScrollView removeFromSuperview];
    
    [self.scrollMenuView removeFromSuperview];
    
    [self setupSubViews];
    
    [self setSelectedPageIndex:self.pageIndex];
}

/**
 选中页码
 
 @param pageIndex 页面下标
 */
- (void)setSelectedPageIndex:(NSInteger)pageIndex
{
    // 当前页面跟传进来的是同一个
    if (self.cacheViewControllerDict.count > 0 && pageIndex == self.pageIndex)
    {
        return;
    }
    
    // 传进来的pageIndex 大于 controllerList 数组的index，会导致越界
    if (pageIndex > self.controllerList.count - 1)
    {
        return;
    }
    
    CGRect frame = CGRectMake(self.pageScrollView.width * pageIndex, 0, self.pageScrollView.width, self.pageScrollView.height);
//    debugLogFrame(frame);
    if (frame.origin.x == self.pageScrollView.contentOffset.x)
    {
        // 滚动时，就调用该方法。任何offset值改变都调用该方法。
        [self scrollViewDidScroll:self.pageScrollView];
    }
    else
    {
        [self.pageScrollView scrollRectToVisible:frame animated:NO];
    }
    
    // 滚动视图减速完成，滚动将停止时，调用该方法。一次有效滑动，只调用一次
    [self scrollViewDidEndDecelerating:self.pageScrollView];
}

/**
 更新菜单栏标题
 
 @param title 标题
 @param index index
 */
- (void)updateMenuItemTitle:(NSString *)title index:(NSInteger)index
{
//    debugMethod();
    if (index < 0 || index > (self.titlesList.count - 1))
    {
        return;
    }
    
    if (title.length == 0)
    {
        return;
    }
    
    NSString *oldTitle = [self titleWithIndex:index];
    
    UIViewController *cacheVC = self.cacheViewControllerDict[[self getKeyWithTitle:oldTitle]];
    if (cacheVC)
    {
        NSString *newKey = [self getKeyWithTitle:title];
        NSString *oldKey = [self getKeyWithTitle:oldTitle];
        [self.cacheViewControllerDict setValue:cacheVC forKey:newKey];
        if (![newKey isEqualToString:oldTitle])
        {
            [self.cacheViewControllerDict setValue:nil forKey:oldKey];
        }
    }
    [self.titlesList replaceObjectAtIndex:index withObject:title];
    [self.scrollMenuView reloadWithView];
}

/**
 更新全部菜单栏标题
 
 @param titles 标题数组
 */
- (void)updateMenuItemTitles:(NSArray *)titles
{
//    debugMethod();
    if (titles.count != self.titlesList.count)
    {
        return;
    }
    
    for (int i=0; i<titles.count; i++)
    {
        NSInteger index = i;
        NSString *title = titles[i];
        if (![title isKindOfClass:[NSString class]] || title.length == 0)
        {
            return;
        }
        NSString *oldTitle = [self titleWithIndex:index];
        UIViewController *cacheVC = self.cacheViewControllerDict[[self getKeyWithTitle:oldTitle]];
        if (cacheVC)
        {
            NSString *newKey = [self getKeyWithTitle:title];
            NSString *oldKey = [self getKeyWithTitle:oldTitle];
            [self.cacheViewControllerDict setValue:cacheVC forKey:newKey];
            if (![newKey isEqualToString:oldKey])
            {
                [self.cacheViewControllerDict setValue:nil forKey:oldKey];
            }
        }
    }
    
    [self.titlesList replaceObjectsInRange:NSMakeRange(0, titles.count) withObjectsFromArray:titles];
    [self.scrollMenuView reloadWithView];
}

/**
 批量插入控制器
 
 @param titles 标题数组
 @param controllers 控制器数组
 @param index 插入的下标
 */
- (void)insertPageChildControllersWithTitles:(NSArray *)titles controllers:(NSArray *)controllers index:(NSInteger)index
{
    index = (index < 0 ? 0 : index);
    index = (index > self.controllerList.count ? self.controllerList.count : index);
    NSInteger tarIndex = index;
    BOOL insertSuccess = NO;
    if (titles.count == controllers.count && controllers.count > 0)
    {
        for (int i=0; i<titles.count; i++)
        {
            NSString *title = titles[i];
            if (title.length == 0 || ([self.titlesList containsObject:title] && ![self respondsToCustomCacheKey]))
            {
                continue;
            }
            insertSuccess = YES;
            [self.titlesList insertObject:title atIndex:tarIndex];
            [self.controllerList insertObject:controllers[i] atIndex:tarIndex];
            tarIndex++;
        }
    }
    if (!insertSuccess)
    {
        return;
    }
    
    NSInteger pageIndex = (index > self.pageIndex ? self.pageIndex : self.pageIndex + controllers.count);
    [self updateViewWithIndex:pageIndex];
}
/**
 根据标题移除控制器
 
 @param title 标题
 */
- (void)removePageControllerWithTitle:(NSString *)title
{
    if ([self respondsToCustomCacheKey])
    {
        return;
    }
    
    NSInteger index = -1;
    for (NSInteger i=0; i<self.titlesList.count; i++)
    {
        if ([self.titlesList[i] isEqualToString:title])
        {
            index = i;
            break;
        }
    }
    if (index == -1)
    {
        return;
    }
    [self removePageControllerWithIndex:index];
}

/**
 根据下标移除控制器
 
 @param index 下标
 */
- (void)removePageControllerWithIndex:(NSInteger)index
{
//    debugMethod();
    if (index < 0 || index > self.titlesList.count || self.titlesList.count == 1)
    {
        return;
    }
    
    NSInteger pageIndex = 0;
    if (self.pageIndex >= index)
    {
        pageIndex = self.pageIndex - 1;
        if (pageIndex < 0)
        {
            pageIndex = 0;
        }
    }
    
    /// 等于 0 先选中 + 1个才能移除
    if (pageIndex == 0)
    {
        [self setSelectedPageIndex:1];
    }
    
    NSString *title = self.titlesList[index];
    [self.titlesList removeObject:self.titlesList[index]];
    [self.controllerList removeObject:self.controllerList[index]];
    
    NSString *key = [self getKeyWithTitle:title];
    
    [self.originInsetBottomDictM removeObjectForKey:key];
    [self.scrollViewCacheDictionryM removeObjectForKey:key];
    [self.cacheViewControllerDict removeObjectForKey:key];
    
    [self updateViewWithIndex:pageIndex];
}

/**
 *  调整标题数组顺序 - 控制器也会跟着调整
 *
 *  @param titleArray 标题数组 需要与原来的titles数组相同
 */
- (void)replaceTitlesArrayForSort:(NSArray *)titleArray
{
    BOOL condition = YES;
    for (NSString *str in titleArray)
    {
        if (![self.titlesList containsObject:str])
        {
            condition = NO;
            break;
        }
    }
    if (!condition || titleArray.count != self.titlesList.count)
        return;
    
    NSMutableArray *resultArrayM = @[].mutableCopy;
    NSInteger currentPage = self.pageIndex;
    for (int i = 0; i < titleArray.count; i++)
    {
        NSString *title = titleArray[i];
        NSInteger oldIndex = [self.titlesList indexOfObject:title];
        /// 等于上次选择的页面 更换之后的页面
        if (currentPage == oldIndex)
        {
            self.pageIndex = i;
        }
        [resultArrayM addObject:self.controllerList[oldIndex]];
    }
    
    [self.titlesList removeAllObjects];
    [self.titlesList addObjectsFromArray:titleArray];
    
    [self.controllerList removeAllObjects];
    [self.controllerList addObjectsFromArray:resultArrayM];
    
    [self updateViewWithIndex:self.pageIndex];
}

/**
 * 刷新悬浮HeaderViewFrame
 
 * YNPageStyleSuspensionTop 样式 1.需要对刷新控件进行特殊处理 2.需要在下拉刷新完成时调用该方法
 * YNPageStyleSuspensionCenter 样式 1.需要在下拉刷新完成时调用该方法
 */
- (void)reloadSuspendHeaderViewFrame
{
    if (self.headerView && ([self isSuspensionTopStyle] || [self isSuspensionBottomStyle]))
    {
        /// 重新初始化headerBgView
        [self initWithHeaderBgView];
        for (int i = 0; i < self.titlesList.count; i++)
        {
            NSString *title = self.titlesList[i];
            if(self.cacheViewControllerDict[[self getKeyWithTitle:title]])
            {
                UIScrollView *scrollView = [self getScrollViewWithPageIndex:i];
                scrollView.contentInset = UIEdgeInsetsMake(_insetTop, 0, 0, 0);
                if ([self isSuspensionBottomStyle])
                {
                    /// 设置偏移量
                    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(_insetTop, 0, 0, 0);
                }
            }
        }
        /// 更新布局
        [self replaceHeaderViewFromTableView];
        [self replaceHeaderViewFromView];
        [self tyz_pageScrollViewDidScrollView:self.currentScrollView];
        [self scrollViewDidScroll:self.pageScrollView];
        if (!self.pageScrollView.isDragging)
        {
            [self scrollViewDidEndDecelerating:self.pageScrollView];
        }
    }
    else if ([self isSuspensionTopPauseStyle])
    {
        /// 重新初始化headerBgView
        [self initWithHeaderBgView];
        [self initWithPageScrollView];
    }
}

/**
 滚动到顶部(置顶)
 
 @param animated 是否动画
 */
- (void)scrollToTop:(BOOL)animated
{
    if ([self isSuspensionTopStyle] || [self isSuspensionBottomStyle])
    {
        [self.currentScrollView setContentOffset:CGPointMake(0, -self.config.tempTopHeight) animated:animated];
    }
    else if ([self isSuspensionTopPauseStyle])
    {
        [self.currentScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:animated];
    }
    else
    {
        [self.currentScrollView setContentOffset:CGPointMake(0, 0) animated:animated];
    }
}

/**
 滚动到某一位置
 
 @param point 点
 @param animated 是否动画
 */
- (void)scrollToContentOffset:(CGPoint)point animated:(BOOL)animated
{
    if ([self isSuspensionTopStyle] || [self isSuspensionBottomStyle])
    {
        [self.currentScrollView setContentOffset:point animated:animated];
    }
    else if ([self isSuspensionTopPauseStyle])
    {
        [self.currentScrollView setContentOffset:point animated:NO];
        [self.bgScrollView setContentOffset:point animated:animated];
    }
    else
    {
        [self.currentScrollView setContentOffset:point animated:animated];
    }
}

/// 更新badge
/// @param badgeValue badgeValue description
/// @param index index description
- (void)updateBadge:(NSInteger)badgeValue index:(NSInteger)index
{
    [self.scrollMenuView updateBadge:badgeValue index:index];
}


#pragma mark - UIScrollViewDelegate
/**
 当开始滚动视图时，调用该方法。一次有效滚动（开始滑动，滑动一小段距离，只要手指不d松开，就算一次滑动），只调用一次

 @param scrollView scrollView description
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    debugMethod();
    if ([self isSuspensionTopPauseStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
        if (scrollView == self.bgScrollView)
        {
            _beginBgScrollOffsetY = scrollView.contentOffset.y;
            _beginCurrentScrollOffsetY = self.currentScrollView.contentOffset.y;
        }
        else
        {
            self.currentScrollView.scrollEnabled = NO;
        }
    }
}

/**
 滑动scrollView，并且手指离开的时调用。一次有效滑动，只调用一次。
 当pagingEnabled属性为YES时，不调用该方法

 @param scrollView scrollView description
 @param decelerate decelerate description
 */
//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset

/**
 滑动视图，当手指离屏幕那一霎那，调用该方法。一次有效滑动，只调用一次

 @param scrollView scrollView description
 @param decelerate 当我们手指离开那一瞬后，视图是否还将继续向前滚动（一段距离），经过测试，decelerate=YES
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//    debugMethod();
    if (scrollView == self.bgScrollView)
    {
        return;
    }
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle])
    {
        if (!decelerate)
        {
            [self scrollViewDidScroll:scrollView];
            [self scrollViewDidEndDecelerating:scrollView];
        }
    }
    else if ([self isSuspensionTopPauseStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
        self.currentScrollView.scrollEnabled = YES;
    }
}

/**
  滚动结束
 滚动视图减速完成，滚动将停止时，调用该方法。一次有效滑动，只调用一次

 @param scrollView scrollView description
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    debugMethod();
    if (scrollView == self.bgScrollView)
    {
        return;
    }
    
    if ([self isSuspensionTopPauseStyle])
    {
        self.currentScrollView.scrollEnabled = YES;
    }
    
    [self replaceHeaderViewFromView];
    [self removeViewController];
    [self.scrollMenuView adjustItemPositionWithCurrentIndex:self.pageIndex];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:didEndDecelerating:)])
    {
        [self.delegate pageViewController:self didEndDecelerating:scrollView];
    }
}

/**
 正在滚动
 滚动时，就调用该方法。任何offset值改变都调用该方法。
 滚动过程中，调用多次

 @param scrollView scrollView description
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    debugMethod();
    if (scrollView == self.bgScrollView)
    {
//        debugLog(@"444444444");
        [self calcuSuspendTopPauseWithBgScrollView:scrollView];
        [self invokeDelegateForScrollWithOffsetY:scrollView.contentOffset.y];
        return;
    }
    
    CGFloat currentPostion = scrollView.contentOffset.x;
    CGFloat offsetX = currentPostion / kScreenWidth;
    CGFloat page = (currentPostion > self.lastPositionX ? ceilf(offsetX) : offsetX);
//    debugLog(@"%s--page=%f; currentPostion=%f; offsetX=%f", __func__, page, currentPostion, offsetX);
    
    // 将headerView 从 tableview 上 放置 view 上
    [self replaceHeaderViewFromTableView];
    
    // 初始化子控制器
    [self initWithViewControllerIndex:page];
    
    CGFloat progress = offsetX - (NSInteger)offsetX;
//    debugLog(@"progress=%f", progress);
    self.lastPositionX = currentPostion;
    
    [self.scrollMenuView adjustItemWithProgress:progress lastIndex:floor(offsetX) currentIndex:ceilf(offsetX)];
    
    /*
     ceil(x) 返回不小于x的最小整数值（返回值为浮点型）。
     floor(x) 返回不大于x的最大整数值（返回值为浮点型）。
     round(x) 返回x的四舍五入整数值（返回值为浮点型）。
     */
//    debugLog(@"offsetX=%f; floor(offsetX)=%f; ceilf(offsetX)=%f", offsetX, floor(offsetX), ceilf(offsetX));
    if (floor(offsetX) == ceilf(offsetX))
    {
        [self.scrollMenuView adjustItemAnimate:YES];
    }
    
    // floor(x) 返回不大于x的最大整数值
    // ceilf(x) 返回不小于x的最小整数值
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:didScroll:progress:formIndex:toIndex:)])
    {
        [self.delegate pageViewController:self didScroll:scrollView progress:progress formIndex:floor(offsetX) toIndex:ceilf(offsetX)];
    }
    
}

#pragma mark - UIScrollView+TYZPage 上对应的block

- (void)tyz_pageScrollViewBeginDragginScrollView:(UIScrollView *)scrollView
{
//    debugMethod();
    _beginBgScrollOffsetY = self.bgScrollView.contentOffset.y;
    _beginCurrentScrollOffsetY = scrollView.contentOffset.y;
}

- (void)tyz_pageScrollViewDidScrollView:(UIScrollView *)scrollView
{
//    debugMethod();
    if ([self isSuspensionBottomStyle] || [self isSuspensionTopStyle])
    {
        if (!_headerViewInTableView) return;
        
        if (scrollView != self.currentScrollView) return;
        NSString *title = [self titleWithIndex:self.pageIndex];
        CGFloat originInsetBottom = [self.originInsetBottomDictM[[self getKeyWithTitle:title]] floatValue];
//        debugLog(@"originInsetBottom=%f", originInsetBottom);
        if ((scrollView.contentInset.bottom - originInsetBottom) > kDEFAULT_INSET_BOTTOM)
        {
//            debugLog(@"if ((scrollView.contentInset.bottom - originInsetBottom) > kDEFAULT_INSET_BOTTOM)");
            scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top, 0, originInsetBottom, 0);
        }
//        debugLog(@"contentoffset=%@", NSStringFromCGPoint(scrollView.contentOffset));
        CGFloat offsetY = scrollView.contentOffset.y;
//        debugLog(@"offsetY=%f", offsetY);
        /// 悬浮临界点
        if (offsetY > -self.scrollMenuView.height - self.config.suspenOffsetY)
        {
//            debugLog(@"offsetY > -self.scrollMenuView.height - self.config.suspenOffsetY");
            self.headerBgView.top = -self.headerBgView.height + offsetY + self.config.suspenOffsetY;
            self.scrollMenuView.top = offsetY + self.config.suspenOffsetY;
            self.supendStatus = YES;
        }
        else
        {
//            debugLog(@"else");
            /// headerView往下拉置顶
            if (offsetY >= -_insetTop)
            {
//                debugLog(@"if (offsetY >= -_insetTop)");
                self.headerBgView.top = -_insetTop;
            }
            else
            {
                if ([self isSuspensionBottomStyle])
                {
                    self.headerBgView.top = offsetY;
                }
            }
            self.scrollMenuView.top = self.headerBgView.bottom;
            self.supendStatus = NO;
        }
        
        [self adjustSectionHeader:scrollView];
        
        [self invokeDelegateForScrollWithOffsetY:offsetY];
        
        [self headerScaleWithOffsetY:offsetY];
        
    }
    else if ([self isSuspensionTopPauseStyle])
    {// 菜单视图悬浮，刷新控件在HeaderView顶部 停顿 类似QQ联系人页面
        [self calcuSuspendTopPauseWithCurrentScrollView:scrollView];
    }
    else
    {
        [self invokeDelegateForScrollWithOffsetY:scrollView.contentOffset.y];
    }
}

/**
 调整scrollMenuView层级，防止TableView Section Header 挡住

 @param scrollView scrollView description
 */
- (void)adjustSectionHeader:(UIScrollView *)scrollView
{
    if (scrollView.subviews.lastObject != self.scrollMenuView)
    {
        [scrollView bringSubviewToFront:self.headerBgView];
        [scrollView bringSubviewToFront:self.scrollMenuView];
    }
}

#pragma mark - TYZPageScrollMenuViewDelegate
- (void)pageScrollMenuViewAddButtonAction:(UIButton *)button
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:didAddButtonAction:)])
    {
        [self.delegate pageViewController:self didAddButtonAction:button];
    }
}

- (void)pageScrollMenuViewItemOnClick:(UIButton *)button index:(NSInteger)index
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:didScrollMenuItem:index:)])
    {
        [self.delegate pageViewController:self didScrollMenuItem:button index:index];
    }
    
    [self setSelectedPageIndex:index];
}


@end
